<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>头像</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="stylesheet" href="../../plugins/mui/mui.min.css">
    <script src="../../js/statistics.js"></script>
    <style type="text/css">
        *{
            box-sizing: border-box;
            font-family: 'Microsoft YaHei';
        }
        body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, form,  input, p, table, th, td ,select,option{
            padding: 0;
            margin: 0;
            list-style: none;
        }
        body{
            padding-top:45px;
            padding-bottom:10px;
            background:#333;
        }
        .clearfix:before{
            display:table;
            content:'';
        }
        .clearfix:after{
            display:table;
            content:'';
            clear:both;
        }
        /*title的样式覆盖*/
        .mui-bar{
            background-color:#2a2c33;
            top:0;
        }
        .mui-bar>a{
            color:#fff;
        }
        .mui-title{
            color:#fff;
        }
        #clipArea{
            width: 100%;
            height: 100vw;
            background: #fff;
            margin: 0 auto;
            position: absolute;
            top: 50%;
            left: 50%;
            -webkit-transform: translateY(-50%) translateX(-50%);
        }
        #clipArea>img{
            width:100%;
            height:100%;
            display:block;
        }
    </style>
</head>
<body>
<header class="mui-bar ">
    <a class=" mui-icon mui-icon-left-nav mui-pull-left" id="back1"></a>
    <h1 class="mui-title">头像</h1>
    <a  class="mui-icon mui-icon-more mui-pull-right" id="openPopover1"></a>
</header>
<div id="clipArea">
    <img src="../../images/my/index/gray.png" id='mainImage'/>
</div>
<div id='map'></div>
<div id="sheet1" class="mui-popover mui-popover-bottom mui-popover-action ">
    <!-- 可选择菜单 -->
    <ul class="mui-table-view">
        <li class="mui-table-view-cell" id='submit1'>
            <a href="#">从相册中选择</a>
        </li>
        <li class="mui-table-view-cell" id='submit2'>
            <a href="#">拍照</a>
        </li>
    </ul>
    <!-- 取消菜单 -->
    <ul class="mui-table-view">
        <li class="mui-table-view-cell">
            <a href="#sheet1"><b>取消</b></a>
        </li>
    </ul>
</div>
<script src="../../plugins/mui/mui.min.js"></script>
<script src="../../js/getApiToken.js"></script>
<script src="../../js/md5.js"></script>
<script type="text/javascript">
    mui.plusReady(function(){
        init();
        //初始化头像页面
        function init(){
            if(plus.storage.getItem('cg_headimgurl')){
                mainImage.src=plus.storage.getItem('cg_headimgurl');
            }
            //关闭等待框
            plus.nativeUI.closeWaiting();
            //显示当前页面
            mui.currentWebview.show('slide-in-right',200);
        }

        //绑定上传头像事件
        submit1.addEventListener("tap",function () {chooseImgFromAlbums();});
        submit2.addEventListener("tap",function () {chooseImgFromPictures();});
		openPopover1.addEventListener("tap",function () {chooseImgFromAlbums();});		
        mainImage.addEventListener("tap",function () {chooseImgFromAlbums();});
        //选择图片后,返回按钮bug
        back1.addEventListener("tap",function () {plus.webview.currentWebview().close();});
        mui.menu = function() {chooseImgFromAlbums()};
        //从相册选择
        function chooseImgFromAlbums(){
//          mui('#sheet1').popover('toggle');
            plus.gallery.pick(function(file) {
                        changeToLocalUrl(file);
                    },
                    function(err) {
                        console.log(JSON.stringify(err));
//                      mui('#sheet1').popover('toggle');
                    },
                    {
                        filter: 'image',
                        multiple: false
                    });
        }
        //拍照选择头像
        function chooseImgFromPictures() {
            mui('#sheet1').popover('toggle');
            var cmr = plus.camera.getCamera();
            cmr.captureImage(function(file) {
                changeToLocalUrl(file);
            }, function(err) {
                mui('#sheet1').popover('toggle');
                console.log(JSON.stringify(err));
            }, {
                index: '2'
            });
        }
        //接受到头像 进行处理跳转
        function changeToLocalUrl(path) {
            plus.io.resolveLocalFileSystemURL(path, function(entry) {
                entry.file( function ( file ) {
                    if(file.size/1024/1024<5){
                        var multiple=1-(file.size/1024/1024/5).toFixed(1);
                        uploadHead(entry.toLocalURL(),multiple);
                        plus.nativeUI.showWaiting('上传中...');
                    }else{
                        mui.toast('图片大于5M,请重新上传');
                    }
                }, function ( e ) {
                    alert( e.message );
                } );
            });
        }
        //把新头像更新到页面
        function uploadHead(imgPath,b) {
            var image = new Image();
            image.src = imgPath;
            image.onload = function() {
                var imgData = getBase64Image(image,b);
                myAjax('personal/user_profile/updateUserHeadimgurl', 'post', {
                    'user_id': plus.storage.getItem('cg_user_id'),
                    'user_token': plus.storage.getItem('cg_user_token'),
                    'headimg':imgData.substring(23)
                }, function(data) {
                	console.log(JSON.stringify(data));
                    if(data.success){
                        //安卓打开
                        download1(_baseUrl+data.path);
                        //ios版本打开
//                        var path=_baseUrl+data.path;
//                        plus.storage.setItem('cg_headimgurl',path);
//                        mainImage.src=path;
//                        //动态修改我的首页 跟个人信息的头像
//                        mainImage.onload=function(){
//                            plus.nativeUI.closeWaiting();
//                            var main = plus.webview.getWebviewById('user.html');//或者通过A页面id获取A页面对象
//                            mui.fire(main, "pageflowrefresh" ,{'userImg':path});//出发A页面的pageflowrefresh方法
//                            var main1 = plus.webview.getWebviewById('my-1.html');//或者通过A页面id获取A页面对象
//                            mui.fire(main1, "pageflowrefresh" ,{'userImg':path});//出发A页面的pageflowrefresh方法
//                            mui.toast('头像修改成功');
//                            plus.webview.currentWebview().close();
//                        }
                    }else{
                        mui.toast(data.error_msg);
                    }
                })
            }
        }
        //将图片压缩转成base64
        function getBase64Image(img,b) {
            var canvas = document.createElement("canvas");
            var width = img.width;
            var height = img.height;
            // calculate the width and height, constraining the proportions
            //图片比例一定的取中间
            var x,y,c,z;
            if (width > height) {
                x=(width-height)/2;
                y=0;
                c=height;
                z=height;
            } else if(width < height){
                x=0;
                y=(height-width)/2;
                c=width;
                z=width;
            }else{
                x=0;
                y=0;
                c=width;
                z=height;
            }
            var clipArea = document.getElementById("clipArea");
            canvas.width = width;   /*设置新的图片的宽度*/
            canvas.height = height; /*设置新的图片的长度*/
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img,x,y,c,z,0,0,width,height); /*绘图*/
            var dataURL = canvas.toDataURL("image/jpeg",.1);
            return dataURL;
        }

        //将图片下载
        function download1(path){
//          plus.io.resolveLocalFileSystemURL( "_doc/userImg/", function( entry ) {
//              // 可通过entry对象操作test.html文件
//              var directoryReader =  entry.createReader();
//              directoryReader.readEntries( function( entries ){
//                      for( i=0; i < entries.length; i++ ) {
//                           entries[i].remove();//遍历每个图片删除
//                      }
                        //图片不存在的时候才下载本地图片
                        var dtask = plus.downloader.createDownload(path, {filename:"_doc/userImg/"}, function(d,status){
                            if ( status == 200 ) {
                                plus.io.resolveLocalFileSystemURL(d.filename, function(entry) {
                                    entry.file( function ( file ) {
                                        //修改本地头像
                                        var path=entry.toLocalURL();
                                        plus.storage.setItem('cg_headimgurl', path);
                                        mainImage.src=entry.toLocalURL();
                                        console.log('修改的头像为'+path);
                                        //动态修改我的首页 跟个人信息的头像
                                        mainImage.onload=function(){
                                            plus.nativeUI.closeWaiting();
                                            var main = plus.webview.getWebviewById('user.html');//或者通过A页面id获取A页面对象
                                            mui.fire(main, "pageflowrefresh" ,{'userImg':path});//出发A页面的pageflowrefresh方法
                                            var main1 = plus.webview.getWebviewById('my-1.html');//或者通过A页面id获取A页面对象
                                            mui.fire(main1, "pageflowrefresh" ,{'userImg':path});//出发A页面的pageflowrefresh方法
                                            mui.toast('头像修改成功');
                                            plus.webview.currentWebview().close();
                                        }

                                    }, function ( e ) {
                                        alert( e.message );
                                    } );
                                });
                            } else {
                                plus.nativeUI.alert("头像下载失败！");
                            }
                        });
                        dtask.start();
//              }, function ( e ) {
//                  alert( "Read entries failed: " + e.message );
//              } );
//          }, function ( e ) {
//              alert( "Resolve file URL failed: " + e.message );
//          } );
        }

    });
</script>
</body>
</html>

